﻿using Digitalmes.Application.Sys.Users;
using Digitalmes.Application.Sys.Users.Commands;
using Digitalmes.Application.Sys.Users.Queries;

namespace Digitalmes.WebApi.Endpoints;

/// <summary>
/// 用户信息终结点。
/// </summary>
public sealed class UserEndpoint : EndpointGroupBase
{
    public override void Map(WebApplication app)
    {
        app.MapGroup(this)
            .RequireAuthorization()
            .MapGet(GetUserPagedListAsync, "list-page")
            .MapGet(GetUserByIdAsync, "{id}")
            .MapGet(GetMineAsync, "mine")
            .MapPost(CreateUserAsync)
            .MapPut(UpdateUserAsync)
            .MapPut(ResetPasswordUserAsync, "reset-password")
            .MapPut(ChangeStatusUserAsync, "change-status")
            .MapPut(DistributeRolesUserAsync, "distribute-roles")
            .MapPost(DeleteUserAsync, "{id}");
    }

    public async Task<IApiResult> GetUserPagedListAsync(ISender sender, [AsParameters] GetUserWithPagedQuery query)
    {
        var result = await sender.Send(query);
        return ApiResult.FromResult(result);
    }

    public async Task<IApiResult> GetUserByIdAsync(ISender sender, long id)
    {
        var result = await sender.Send(new GetUserByIdQuery(id));
        return ApiResult.FromResult(result);
    }

    public async Task<IApiResult> GetMineAsync(ISender sender, ICurrentUser currentUser)
    {
        var result = await sender.Send(new GetUserByIdQuery(currentUser.UserId ?? 0));
        return ApiResult.FromResult(result);
    }

    public async Task<IApiResult> CreateUserAsync(ISender sender, SysUserDto dto)
    {
        var result = await sender.Send(new CreateUserCommand(dto));
        return ApiResult.FromResult(result);
    }

    public async Task<IApiResult> UpdateUserAsync(ISender sender, SysUserDto dto)
    {
        var result = await sender.Send(new UpdateUserCommand(dto));
        return ApiResult.FromResult(result);
    }

    public async Task<IApiResult> ResetPasswordUserAsync(ISender sender, ResetPasswordCommand command)
    {
        var result = await sender.Send(command);
        return ApiResult.FromResult(result);
    }

    public async Task<IApiResult> ChangeStatusUserAsync(ISender sender, ChangeUserStatusCommand command)
    {
        var result = await sender.Send(command);
        return ApiResult.FromResult(result);
    }

    public async Task<IApiResult> DistributeRolesUserAsync(ISender sender, DistributeRolesToUserCommand command)
    {
        var result = await sender.Send(command);
        return ApiResult.FromResult(result);
    }

    public async Task<IApiResult> DeleteUserAsync(ISender sender, long id)
    {
        var result = await sender.Send(new DeleteUserCommand(id));
        return ApiResult.FromResult(result);
    }
}
